package com.huzz.security.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.huzz.security.util.captcha.CaptchaType;
import com.huzz.security.util.RedisUtil;
import com.huzz.security.util.Result;
import com.huzz.security.util.uuid.IdUtils;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

/**
 * @Name 名称
 * @Description 描述
 * @Author 童年的纸飞机
 * @Since 2023-01-2023/1/12 11:37
 */
@RestController
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Value("${captcha.type}")
    private String captchaType;

    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/captcha")
    public Result Captcha() throws IOException {
        String key = IdUtils.simpleUUID();

        String capStr, code = null;
        BufferedImage image = null;

        // math类型验证码
        if (CaptchaType.MATH.equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);

        }

        // char类型验证码
        if (CaptchaType.CHAR.equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);

//        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        redisUtil.hset("captcha", key, code, 120);

        return Result.success(
                MapUtil.builder()
                        .put("userKey", key)
                        .put("captcherImg", "data:image/jpeg;base64," + Base64.encode(os.toByteArray()))
                        .build()
        );
    }

}
